package vip.finance.makemoney.config.feign;

import cn.hutool.http.HttpRequest;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import vip.finance.makemoney.common.Constant;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 杨滨
 * @date 2023年02月14日
 */
@Slf4j
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            if (methodKey.contains("Snow")) {
                // 这里直接拿到我们抛出的异常信息
                String message = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
                if (message != null && message.contains("遇到错误，请刷新页面或者重新登录帐号后再试")) {
                    Constant.XQ_A_TOKEN = String.valueOf(HttpRequest.get("https://xueqiu.com").execute().getCookie("xq_a_token"));
                    log.info("自动重新获取雪球token成功");
                    return new Exception("雪球token失效，已自动重新获取token成功");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }
}
